<?php
/**
 * Created by PhpStorm.
 * User: zyh
 * Date: 2018/5/29
 * Time: 下午8:27
 */

namespace app\admin\model;


use GatewayClient\Gateway;
use think\Cache;
use think\console\Output;
use think\Model;

class Rewards extends Model
{
    //获取投注合计信息
    public function getRewardsInfo($gid)
    {
        $game = null;
        if ($gid==null){
            //如果没有iD就选择最后一个比赛  最后一个比赛发给客户端
            $game = Game::get(function ($query){
                $query->order('id','desc');
            });
            $gid = $game['id'];
        }else{
            $game = Game::get($gid);
        }


        $data = [];
        //基本统计数据
        $data['id'] = $gid;
        $data['status'] = $game['status'];
        $data['kou'] = $game['status'] <= 1 ? 0 :Cache::get('kou');
        $data['red_reward']     = $this::where(['direction'=>1,"gid"=>$gid])->sum("reward");
        $data['red_total']      = $this::where(['direction'=>1,"gid"=>$gid])->sum("reward");
        $data['blue_reward']    = $this::where(['direction'=>2,"gid"=>$gid])->sum("reward");
        $data['blue_total']     = $this::where(['direction'=>2,"gid"=>$gid])->sum("reward");
        //平台
        $data['system']      = $this::where(['direction'=>0,"gid"=>$gid])->sum('reward');

        $info_data = [];
        //红方详细


        $info_data['red_kaipen'] = $this::where(['kid'=>10,'direction'=>1,"gid"=>$gid])->sum('reward');
        $info_data['red_qikou']  = $this::where(['kid'=>7,'direction'=>1,"gid"=>$gid])->sum('reward');
        $info_data['red_liukou'] = $this::where(['kid'=>6,'direction'=>1,"gid"=>$gid])->sum('reward');
        $info_data['red_wukou']  = $this::where(['kid'=>5,'direction'=>1,"gid"=>$gid])->sum('reward');

        //蓝方详细
        $info_data['blue_kaipen'] = $this::where(['kid'=>10,'direction'=>2,"gid"=>$gid])->sum('reward');
        $info_data['blue_qikou']  = $this::where(['kid'=>7,'direction'=>2,"gid"=>$gid])->sum('reward');
        $info_data['blue_liukou'] = $this::where(['kid'=>6,'direction'=>2,"gid"=>$gid])->sum('reward');
        $info_data['blue_wukou']  = $this::where(['kid'=>5,'direction'=>2,"gid"=>$gid])->sum('reward');

        //根据接放扣身份重新计算显示分
        $kou7 = $this::where(['kid'=>7,'gid'=>$gid])->find()['kou'];
        if ($kou7 == 1){
            $info_data['blue_qikou']  = $info_data['blue_qikou']  * 10 / 7;
        }else{
            $info_data['red_qikou']  = $info_data['red_qikou']  * 10 / 7;
        }

        $kou6 = $this::where(['kid'=>6,'gid'=>$gid])->find()['kou'];
        if ($kou6 == 1){
            $info_data['blue_liukou'] = $info_data['blue_liukou'] * 10 / 6 ;
        }else{
            $info_data['red_liukou'] = $info_data['red_liukou'] * 10 / 6 ;
        }

        $kou5 = $this::where(['kid'=>5,'gid'=>$gid])->find()['kou'];
        if ($kou5 == 1){
            $info_data['blue_wukou']  = $info_data['blue_wukou']  * 10 / 5;
        }else{
            $info_data['red_wukou']  = $info_data['red_wukou']  * 10 / 5;
        }

        $data['info'] = $info_data;
        return $data;
    }

    //新增投注信息
    public function insertReward($data)
    {
        //余额不足
        if (User::get($data['uid'])['score']<$data['reward']) return false;
        User::get($data['uid'])->setDec('score',$data['reward']);
        return $this->save($data);
    }

    //结算上一个状态信息  $kid是上一个阶段的KID 需要处理的KID
    public function settlement($gid,$kid,$winner=null)
    {
        $R = 0;
        //开始切换的到开盆不需要结算
        if ($kid == 0) return null;

        //
        $red_reward = $this::where(['kid'=>$kid,'direction'=>1,"gid"=>$gid])->sum('reward');
        $blue_reward = $this::where(['kid'=>$kid,'direction'=>2,"gid"=>$gid])->sum('reward');
        echo Cache::get("kou")."<br/>";
//        echo $red_reward."----".$blue_reward."<br/>";
        //原始数据在扣
        if (Cache::get("kou") == 1){
            $blue_reward = $blue_reward * 10 / $kid;
        }else if (Cache::get("kou") == 2){
            $red_reward = $red_reward *  10 / $kid;
        }
//        echo $red_reward."----".$blue_reward;

        //获取双方所有的投注
        if ($red_reward - $blue_reward != 0) {
            //比较大小  然后把超出投注 按照时间顺序从后到前设置依次减掉，并设置为踢出
            $red_reward > $blue_reward ? $R = 1 : $R = 2;
            //差额  开盆倍率不变  其他各扣 分别计算
            $dec = 0;
            if ($dec > 0 && $R == 1){
                $dec = $red_reward - $blue_reward;
            }else{
                $dec = abs($red_reward - $blue_reward) * $kid /10;
            }

            $rs = $this::where(['kid' => $kid, 'direction' => $R, 'gid' => $gid])->order('create_time', 'desc')->select();
            foreach ($rs as $k => $v) {
                if ($dec == 0) break;
                //如果一条记录足够踢出
                if ($v['reward'] >= $dec) {
                    $this::get($v['id'])->setDec('reward', $dec);
                    $this::get($v['id'])->save(['kill_reward' => $dec]);
                    //将踢出的点数返回用户账户
                    $uid = $this::get($v['id'])->field('uid')->find()['uid'];
                    User::get($uid)->setInc('score',$dec);
                    break;
                } else {
                    //如果一条记录不够踢出数
                    $inc = $this::get($v['id'])->field("reward")->find()['reward'];
                    $this::get($v['id'])->save(['reward' => 0, 'kill_reward' => $v['reward']]);
                    //将踢出的点数返回用户账户
                    $uid = $this::get($v['id'])->field('uid')->find()['uid'];
                    User::get($uid)->setInc('score',$inc);

                    $dec -= $v['reward'];
                    continue;
                }
            }

        }else{
            //假如出现从开盆没有放扣出现 默认给红方
            $R = Cache::get("kou",1);
        }
        if ($winner == null) {
            return $R;
        }

        //参与的玩家
        $players = $this::where(['gid'=>$gid])->distinct(true)->field('uid')->select();
        //结算面板
        $arr = [];
        foreach ($players as $v){
            $kou = [10,7,6,5];
            $wintotal = 0;
            $losetotal = 0;
            $taxtotle = 0;
            foreach ($kou as $v1){
                //每扣投注
                //该用户所有本阶段投注
                $rewards = $this::where(['uid'=>$v['uid'],'gid'=>$gid,'kid'=>$v1])->select();
                //逐条处理每天记录输赢
                //每条投注都单独计算输赢
                foreach ($rewards as $id => $reward){
                    $win = 0;
                    $lose = 0;

                    //首选计算输赢 所有投注了胜方的都要赢
                    if ($reward['direction'] == $winner){
                        if ($reward['kou'] == $reward['direction']){
                            //放扣
                            $win = $reward['reward'] * $reward['kid'] / 10;
                        }else{
                            //接扣
                            $win = $reward['reward'] * 10 /$reward['kid'];
                        }

                    }else{
                        $lose = $reward['reward'];
                    }
                    //再分别计算赢的具体数值
                    $reward->win = $win;
                    $reward->lose = $lose;
                    $reward->tax = $win * 0.1 ;
                    $reward->save();

                    //给用户积分添加赢钱进账
                    if ($win>0){
                        User::get($v['uid'])->setInc('score',$reward->win - $reward->tax);
                    }

                    $wintotal += $win;
                    $losetotal += $lose;
                    $taxtotle += $reward->tax;
                }
            }
            $record = new Record();
            $record['gid'] = $gid;
            $record['uid'] = $v['uid'];
            $record['win'] = $wintotal;
            $record['lose'] = $losetotal;
            $record['tax'] = $taxtotle;
            $record['create_time'] = date("Y-m:d H:i:s");
            $record->save();
        }
        return -1;
//        Gateway::sendToGroup("admin",json_encode(['type'=>"result","data"=>[]]));
    }

}